package com.wsc.wsckeeper.persistence;

import java.sql.SQLException;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.wsc.wsckeeper.R;
import com.wsc.wsckeeper.app.KApplication;
import com.wsc.wsckeeper.mock.MockData;
import com.wsc.wsckeeper.model.entity.AccountE;
import com.wsc.wsckeeper.model.entity.CardE;
import com.wsc.wsckeeper.model.entity.CardTypeE;
import com.wsc.wsckeeper.model.entity.CurrencyE;
import com.wsc.wsckeeper.utils.DialogUtils;

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

	public static final String DATABASE_NAME = "keeper.db";

	private static final int DATABASE_VERSION = 48;
	
	public DatabaseHelper(Context context) {
		super(context, getDbName(), null, DATABASE_VERSION, R.raw.ormlite_config);
	}

	private static String getDbName() {
		return DATABASE_NAME;
	}

	@Override
	public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {

		try {
			TableUtils.createTable(connectionSource, CurrencyE.class);
			TableUtils.createTable(connectionSource, CardTypeE.class);
			TableUtils.createTable(connectionSource, CardE.class);
			TableUtils.createTable(connectionSource, AccountE.class);

			MockData.addData();
		} catch (SQLException e) {
			DialogUtils.showException(KApplication.getContext(), e);
		} catch (Exception e) {
			DialogUtils.showException(KApplication.getContext(), e);
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVer, int newVer) {
		try {
			TableUtils.dropTable(connectionSource, CurrencyE.class, true);
			TableUtils.dropTable(connectionSource, CardTypeE.class, true);
			TableUtils.dropTable(connectionSource, CardE.class, true);
			TableUtils.dropTable(connectionSource, AccountE.class, true);
			onCreate(db, connectionSource);
		} catch (SQLException e) {
			DialogUtils.showException(KApplication.getContext(), e);
		}
	}
}
